<?php
namespace app\wempapi\controller;
use app\common\controller\Frontend;
use app\weapp\library\WeAppApi;
use app\wempapi\model\MpWework;
use think\facade\Session;
class Wework extends Frontend
{
    protected $noNeedLogin = ['sessioncode'];

    public function sessioncode(){
        if($this->request->isPost()){
            $code = $this->request->post('code');
            $weAppApi = new WeAppApi();
            $res = $weAppApi->sessioncode($code);
            if($res === false){
                $this->error($weAppApi->Message());
            }else{
                /**
                 * "userid": "USERID","session_key": "kJtdi6RF+Dv67QkbLlPGjw==",
                 */
                $mpuser = Session::get('mpwework');
                $mpwework = MpWework::where('id',$mpuser['id'])->find();
                $mpwework->userid = $res['userid'];
                $mpwework->status = 1;
                $mpwework->save();
                $mpuser = $mpwework->toArray();
                $mpuser['session_key'] = $res['session_key'];
                Session::set('mpwework',$mpuser);
                $this->success('登录成功',$mpuser);
            }
        }
    }
}